import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
  DownloadOutlined,
  SyncOutlined, SearchOutlined, UndoOutlined,
} from '@ant-design/icons';
import {
  Button,
  message,
  Form,
  DatePicker,
  Upload,
  UploadProps,
  Row,
  Col,
  Input,
  Popconfirm,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import moment from 'moment';
import '@/assets/css/index.less';
import {
  batchDelete,
  deleteWatchRecordById,
  getWatcherRecordList,
  insertWatchRecord,
  updateWatchRecord,
} from '@/services/watcherRequestManager';
import { GMTTimeToNormal, formatDate, formatDateDayjs } from '@/utils/formatDate';
import onExportBasicExcel from '@/utils/exportBasicExcel';
import axios from 'axios';
import {getUserInfoList} from "@/services/groupNumber";
const { RangePicker } = DatePicker;
/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */

/**
 *  Delete node
 * @zh-CN 删除多个节点
 *
 * @param selectedRows
 */

const onChange = (e: RadioChangeEvent) => {
  setApproved(e.target.value);
};

const WatcherTableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.WatcherList>();
  const [selectedRows, setSelectedRows] = useState<API.WatcherList[]>();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(40);
  const [dataArray, setDataArray] = useState([]);
  const [fileList, setFileList] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });
  //初始化搜索区域
  const [form] = Form.useForm();
  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
    setPagination({ ...pagination });
  };

  const uploadProps: UploadProps = {
    onChange({ file, fileList }) {
      console.log(file, fileList);
      if (file.status !== 'uploading') {
        console.log(file, fileList);
      }
    },
    async customRequest(param) {
      const { onSuccess, onError, file, onProgress } = param;
      const config = {
        headers: { 'content-type': 'multipart/form-data' },
        onUploadProgress: (event) => {
          console.log(event.loaded, event.total);

          // const percent = Math.floor((event.loaded / event.total) * 100);
          // if(percent === 100){
          //     setTimeout(()=>setProgress(0), 1000)
          // }
          // onProgress({percent: (event.loaded / event.total) * 100});
        },
      };
      let formData = new FormData();
      formData.append('file', file);
      try {
        const response = await axios.post('/api/v1/watch/uploadExcel', formData, config);

        if (response.data.code === '0') {
          setFileList([]);
          onSuccess(response);
          queryData();
        }
      } catch (error) {
        message.error(error.response.data.data);
        onError({ error });
      }
    },
  };

  const queryData = async () => {
    let values = form.getFieldsValue();
    if (values.dataDate != null && values.dataDate != undefined) {
      values.startTime = moment(values.dataDate[0]).format('YYYY-MM-DD') + ' 00:00:00';
      values.endTime = moment(values.dataDate[1]).format('YYYY-MM-DD') + ' 23:59:59';
    }

    const params = {
      page: page,
      pageSize: pageSize,
    };

    const msg = await getWatcherRecordList(params, values);
    const dataArray = formatDate(msg.data && msg.data.watchRecordList, 'watchDate', 'YYYY-MM-DD');
    setDataArray(dataArray);
    setPagination({ ...pagination, total: msg.data.total });
  };
  useEffect(() => {
    queryData();
  }, [page, pageSize]);
  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="关键字" name="keyWord">
                <Input
                  placeholder="请输入关键字"
                  onChange={() => {
                    queryData();
                  }}
                />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item label="值班日期范围" name="dataDate">
                <RangePicker
                  onChange={() => {
                    queryData();
                  }}
                />
              </Form.Item>
            </Col>

            <Col
              span={6}
              offset={2}
              className="basic-search-form-submit-btn"
              style={{ display: 'flex', justifyContent: 'flex-end' }}
            >
              <Button
                onClick={() => {
                  form.resetFields();
                  queryData();
                }}
              >                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };

  const columns: ProColumns<API.WatcherList>[] = [
    {
      title: 'id',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'id',
      // render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '值班日期',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'watchDate',
      valueType: 'date',
      // sorter: (a, b) => {
      //   return new Date(a.watchDate) - new Date(b.watchDate);
      // },
    },
    {
      title: '值班领导',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'watchLeader',
    },
    {
      title: '主班处长',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'watchHead',
    },
    {
      title: '责任单位',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'watchReplaceHead',
    },
/*    {
      title: '车队值班员',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'convoyWatchers',
    },*/
    {
      title: '值班员',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'watchMan',
    },
    {
      title: '车队值班员',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'convoyWatchers',
    },
    {
      title: '添加时间',
      align: 'center',

      hideInSearch: true,
      dataIndex: 'createdTime',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            handleUpdateModalVisible(true);
            record.watchDate = moment(record.watchDate);
            setCurrentRow(record);
          }}
        >
          <Button className={'buttonMargin'} shape={'round'} type="primary" icon={<EditOutlined />}>
            编辑
          </Button>
        </a>,
        <Popconfirm title="确定是否删除?" onConfirm={() => handleRemove(record)} key="delete">
          <a style={{ color: 'red' }}>
            <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
              删除
            </Button>
          </a>
        </Popconfirm>,
      ],
    },
  ];

  const formLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };

  const handleAdd = async (fields: any) => {
    const hide = message.loading('正在添加');

    try {
      await insertWatchRecord({ ...fields });
      hide();
      queryData();
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败，请重试!');
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: FormValueType) => {
    const hide = message.loading('正在更新');
    fields.watchDate = moment(fields.watchDate).format('YYYY-MM-DD') + ' 00:00:00';
    try {
      await updateWatchRecord({
        ...fields,
      });
      hide();
      queryData();
      message.success('修改成功');
      return true;
    } catch (error) {
      hide();
      message.error('修改失败，请重试!');
      return false;
    }
  };
  const handleRemove = async (selectedRows: any) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      await deleteWatchRecordById({
        id: selectedRows.id,
      });
      hide();
      queryData();

      message.success('已删除！');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败！');
      return false;
    }
  };
  const [userList,setUserList ] = useState([])
  const getAllList = async (p=1,ps=1000)=>{
    const msg = await getWatcherRecordList({page:p,pageSize:ps},{});
    let pf = userList
    msg.data.watchRecordList.map(i=>{
      pf.push(i)
    })
    setUserList(pf)
    if(userList.length<msg.data.total){
      getAllList(++p)
    }else{
      return
    }
  }

  const exportAll = async()=>{
    setUserList([])
    await getAllList()
    const timeNow = new Date();
    const formattedData = formatDate(userList, 'watchDate', 'YYYY-MM-DD');
    //remove 操作 一栏
    columns.pop(); //删除‘操作’
    columns.pop(); //删除‘添加时间’
    columns.shift(); //删除‘id’
    onExportBasicExcel(
      '值班管理' + timeNow.toLocaleString() + '.xlsx',
      'Sheet1',
      columns,
      userList,
    );
  }
  const hideTableAlert = () => {
    const tableAlertElement = document.querySelector('.ant-pro-table-alert');
    tableAlertElement.setAttribute('style', 'display: none');
  };
  const handleBatchDelete = async (selectedRows: any) => {
    let idArray = [];
    if (!selectedRows || selectedRows.length === 0) {
      message.error('请选择所要删除的行！');
      return;
    }
    selectedRows.forEach((element) => {
      idArray.push(element.id);
    });
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      await batchDelete(idArray);
      hide();
      queryData();

      message.success('已删除！');
      hideTableAlert();
      return true;
    } catch (error) {
      hide();
      hideTableAlert();
      message.error('删除失败！');
      return false;
    }
  };
  return (
    <PageContainer>
      {_initSearchForm()}
      <ProTable<API.WatcherList, API.PageParams>
        headerTitle="值班信息列表"
        actionRef={actionRef}
        rowKey="id"
        tableStyle={{ textAlign: 'center' }}
        options={false}
        search={false}
        pagination={pagination}
        dataSource={dataArray}
        onChange={handleTableChange}
        selectedRowKeys={[]}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleUpdateModalVisible(true);
            }}
          >
            <PlusOutlined />
            添加
          </Button>,

          <Popconfirm
            title="确定是否批量删除?"
            onConfirm={() => handleBatchDelete(selectedRows)}
            key="delete"
          >
            <Button type="primary" danger key="danger">
              <DeleteOutlined /> 批量删除
            </Button>
          </Popconfirm>,

          <Button onClick={() => {}}>
            <Upload {...uploadProps} fileList={fileList}>
              <UploadOutlined />
              导入Excel
            </Upload>
          </Button>,

          <Button
            name="download"
            type="primary"
            onClick={() => {
              if (selectedRows === undefined) {
                message.error('请选择要导出的数据！');
              } else {
                const timeNow = new Date();
                const formattedData = formatDate(selectedRows, 'watchDate', 'YYYY-MM-DD');
                //remove 操作 一栏
                columns.pop(); //删除‘操作’
                columns.pop(); //删除‘添加时间’
                columns.shift(); //删除‘id’
                onExportBasicExcel(
                  '值班管理' + timeNow.toLocaleString() + '.xlsx',
                  'Sheet1',
                  columns,
                  formattedData,
                );
              }
            }}
          >
            <DownloadOutlined />
            导出Excel
          </Button>,
          <Button
            name="download"
            type="primary"
            onClick={() => {
              exportAll()
            }}
          >
            <DownloadOutlined />
            全部导出
          </Button>,
          <Button
            name="download"
            type="primary"
            onClick={() => {
              queryData();
            }}
          >
            <SyncOutlined />
            刷新
          </Button>,
          <Button type="primary" key="downloadDemo">
            <a href="/backup/值班管理模板.xlsx" download="值班信息导入模板.xlsx">
              下载excel模板
            </a>
          </Button>
        ]}
        // request={async () => {
        //   // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        //   // 如果需要转化参数可以在这里进行修改
        //  const msg = await getWatcherRecordList();
        //   setPagination({...pagination,total:msg.data.total})
        //   return {
        //     data: formatDate(msg.data.watchRecordList, "watchDate", "YYYY-MM-DD") ,
        //     // success 请返回 true，
        //     // 不然 table 会停止解析数据，即使有数据
        //     success: msg.message==='success',
        //     // 不传会使用 data 的长度，如果是分页一定要传
        //     // total: number,
        //   };
        // }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      <UpdateForm
        onSubmit={async (value) => {
          let success;

          if (!currentRow) {
            success = await handleAdd(value);
            setCurrentRow(undefined);
          } else {
            value.id = currentRow.id;
            success = await handleUpdate(value);
          }
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
        key={new Date().getTime()}
      />
    </PageContainer>
  );
};

export default WatcherTableList;
